package com.blackhorse.utils;


import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeoutException;

public class ConnectionUtils {

    private static ConnectionFactory connectionFactory;
    private static String host;
    private static String port;
    private static String username;
    private static String password;
    private static String virtualHost;

    static {
        Properties properties = new Properties();
        InputStream inputStream = ConnectionUtils.class.getClassLoader()
                .getResourceAsStream("rabbitmq.properties");
        try {
            properties.load(inputStream);
            host = properties.getProperty("host");
            port = properties.getProperty("port");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            virtualHost = properties.getProperty("virtualHost");
            //创建连接工厂
            connectionFactory = new ConnectionFactory();
            //rabbitmq服务ip地址和端口，默认为localhost
            connectionFactory.setHost(host);
            connectionFactory.setPort(Integer.parseInt(port));
            //rabbitmq服务虚拟主机名：默认为/
            connectionFactory.setVirtualHost(virtualHost);
            //用户名，默认guest
            connectionFactory.setUsername(username);
            //密码，默认guest
            connectionFactory.setPassword(password);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static ConnectionFactory getConnectionFactory(){
        return connectionFactory;
    }

    public static Connection getConnection() throws IOException, TimeoutException {
        return connectionFactory.newConnection();
    }

    public static void close(Channel channel, Connection connection) {
        //释放资源
        try {
            if (channel != null) {
                channel.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void close(Connection connection) {
        close(null, connection);
    }
}
